/**
 * 
 */
package org.mspring.mlog.api.spider.service.impl;

import java.net.URL;
import java.util.Date;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.mspring.mlog.api.spider.entity.SpiderPost;
import org.mspring.mlog.api.spider.service.SpiderPostService;
import org.mspring.mlog.entity.Attachment;
import org.mspring.mlog.entity.News;
import org.mspring.mlog.entity.NewsCatalog;
import org.mspring.mlog.entity.security.User;
import org.mspring.mlog.service.AttachmentService;
import org.mspring.mlog.service.NewsService;
import org.mspring.mlog.utils.UploadUtils;
import org.mspring.platform.dao.hibernate.GenericDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Gao Youbo
 * @since 2013-5-3
 * @description
 * @TODO
 */
@Service
@Transactional
public class SpiderPostServiceImpl extends GenericDao<SpiderPost, Long> implements SpiderPostService {

    @Autowired
    private NewsService newsService;

    @Autowired
    private AttachmentService attachmentService;

    @Override
    public SpiderPost createSpiderPost(SpiderPost spiderPost) {
        // TODO Auto-generated method stub
        spiderPost.setCreateTime(new Date());
        spiderPost.setPosted(false);
        return save(spiderPost);
    }

    @Override
    public boolean exists(String sourceUrl) {
        // TODO Auto-generated method stub
        int count = getHibernateTemplate().count("select count(*) from SpiderPost p where p.sourceUrl = ?", sourceUrl);
        return count > 0;
    }

    @Override
    public void changePosted(Boolean posted, Long... id) {
        // TODO Auto-generated method stub
        if (posted == null || id == null) {
            return;
        }
        for (Long i : id) {
            executeUpdate("update SpiderPost sp set sp.posted = ? where sp.id = ?", new Object[] { posted, i });
        }
    }

    @Override
    public void publishPost(Long author, Long catalog, SpiderPost post) {
        // TODO Auto-generated method stub
        if (post == null) {
            return;
        }
        News news = new News();
        news.setTitle(post.getTitle());
        news.setContent(post.getContent());
        news.setCatalog(new NewsCatalog(catalog));
        news.setCreateTime(new Date());
        news.setStatus(News.Status.PUBLISH);
        news.setSourceSite(post.getSourceSite());
        news.setSourceUrl(post.getSourceUrl());
        news.setAuthor(new User(author));
        news = newsService.save(news);
        changePosted(true, post.getId());

        // 处理附件图片
        Document doc = Jsoup.parse(news.getContent());
        Elements images = doc.select("img");
        for (int i = 0; i < images.size(); i++) {
            Element image = images.get(i);
            String src = image.attr("src");
            try {
                URL url = new URL(src);
                Attachment attachment = attachmentService.createAttachment(news.getAuthor().getId(), url, Attachment.AttachFromType.FROM_NEWS, news.getId().toString());
                image.attr("src", UploadUtils.UPLOAD_FOLDER + attachment.getPath());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        String content = doc.html();
        news.setContent(content);
        newsService.update(news);
    }

    @Override
    public List<SpiderPost> findByPublishRule(Long publishRuleId) {
        // TODO Auto-generated method stub
        return list("select p from SpiderPost p where p.publishRule = ? and p.posted = ?", publishRuleId, false);
    }

}
